<?php

namespace App\Services\Stock;

use App\CodeResponse;
use App\Enum;
use App\Models\Stock\ProductStock;
use App\Repositories\Basic\ProductRepository;
use App\Repositories\Stock\StockTransferItemRepository;
use App\Repositories\Stock\StockTransferRepository;
use App\Services\BaseService;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StockTransferItemService extends BaseService
{

    public function createItem($transferId, $params)
    {
        $result=$this->checkGetResult($params, $transferId);
        $params['transfer_id'] = $transferId;
        //获取库存商品单价与数量
        $params['price']=$result['out_product_Stock']['cost_price'];

        $params['total_price'] = cal_total_price($params['price'], $params['num']);

        DB::beginTransaction();
        try {
            $res=app(StockTransferItemRepository::class)->create($params);
            StockTransferService::getInstance()->saveTotalCostPrice($res['transfer_id']);
            DB::commit();
            return $res;
        }catch (QueryException $exception){
            DB::rollBack();
            Log::error($exception->getMessage());
            return false;
        }
    }


    public function updateItem($id, $params)
    {
        $result=$this->checkGetResult($params, 0, $id);
        $params['price']=$result['out_product_Stock']['cost_price'];
        $params['total_price'] = cal_total_price($params['price'], $params['num']);
        DB::beginTransaction();
        try {
            $res=app(StockTransferItemRepository::class)->update($id, $params);
            StockTransferService::getInstance()->saveTotalCostPrice($res['transfer_id']);
            DB::commit();
            return $res;
        }catch (QueryException $exception){
            DB::rollBack();
            Log::error($exception->getMessage());
            return false;
        }

    }

    public function deleteItem($id)
    {
        $params=['is_enable'=>Enum::IS_ENABLE_FALSE];
        DB::beginTransaction();
        try {
            $res=app(StockTransferItemRepository::class)->update($id, $params);
            StockTransferService::getInstance()->saveTotalCostPrice($res['transfer_id']);
            DB::commit();
            return true;
        }catch (QueryException $exception){
            DB::rollBack();
            Log::error($exception->getMessage());
            return false;
        }

    }

    protected function checkGetResult($params, $transferId = 0, $id = 0)
    {
        $result = [];

        if ($id) {
            $result['item'] = app(StockTransferItemRepository::class)->where(['is_enable' => Enum::IS_ENABLE_TRUE])->getById($id);
            if (!$result['item']) {
                $this->throwBusinessException(CodeResponse::FAIL, '查询不到订单条目，id 错误');
            }
            $transferId = $result['item']['transfer_id'];
        }

        if ($transferId) {
            //检查订单有效
            $result['transfer'] = app(StockTransferRepository::class)->getById($transferId);
            if (!$result['transfer']) {
                $this->throwBusinessException(CodeResponse::FAIL, '查询不到转移单，transfer_id 或者id 错误');
            }
        }

        //检查产品有效
        $result['product'] = app(ProductRepository::class)->getById($params['product_id']);

        if (!$result['product']) {
            $this->throwBusinessException(CodeResponse::FAIL, '查询不到产品，product_id 错误');
        }

        //查询出库产品库存是否存在，且不能小于转移量
       $outProductStock=ProductStock::select(['id','num','cost_price','total_cost_price'])
           ->where('storage_id',$result['transfer']['out_storage_id'])
           ->where('product_id',$params['product_id'])
           ->first();
        if(!$outProductStock){
            $this->throwBusinessException(CodeResponse::FAIL, '查询不到出库产品库存');
        }

        if($outProductStock['num']<$params['num']){
            $this->throwBusinessException(CodeResponse::FAIL, '出库产品数量不足');
        }
        $result['out_product_Stock']=$outProductStock;

        return $result;
    }


}